package com.pai4j.common.util;

import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 事务后置处理工具类
 * 提供了一个静态方法来注册一个任务，在事务提交后执行
 */
public class TransactionSyncManagerUtil {
    
    
        private static ExecutorService executorService = Executors.newFixedThreadPool(10);
        
        /**
         *  事务提交后异步处理
         * @param task
         */
        public static void registerSynchronization(final Runnable task) {
            
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCommit() {
                    executorService.execute(task);
                }
            });
        }
        
        /**
         * 事务提交后同步处理
         *
         * @param task
         */
        public static void afterCommit(final Runnable task) {
            
            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
                @Override
                public void afterCommit() {
                    task.run();
                }
            });
        }
}

